package control;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.ItemData;
import dao.UserData;

import model.Cart;
import model.Item;

/**
 * Servlet implementation class ShoppingCart
 */
public class ShoppingCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShoppingCart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		String email = (String) session.getAttribute("email");
		ArrayList<Long> list = (ArrayList<Long>)session.getAttribute("idBuy");
		if (cart == null) {
			cart = new Cart();
			session.setAttribute("cart", cart);
		}
		if (list==null) {
			list = new ArrayList<Long>();
			session.setAttribute("idBuy", list);
		}
		String idItem = request.getParameter("idItem");
		String q = request.getParameter("quantity");
		String b = request.getParameter("idBuy");
		long id = 0,idBuy =0;
		int quantity = 0;
		String url = "/yourCart.jsp";
		
		try {
			id = Long.parseLong(idItem);
			quantity = Integer.parseInt(q);
			idBuy = Long.parseLong(b);
			if (list.indexOf(idBuy)==-1) {
				list.add(idBuy);
				cart.insertItem(ItemData.getItem(id), quantity);
			}
		} catch (Exception e) {
			url= "/shopAvatar.jsp";
			request.setAttribute("err", "Bạn nhập số sai định dạng xin mời bạn nhập lại");
		}
		RequestDispatcher rd = getServletContext().getRequestDispatcher(
				url);
		rd.forward(request, response);
	}

}
